package com.ruoyi.auth.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.hl.SmsTest;
import com.ruoyi.auth.form.*;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.User;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.user.api.RemoteUserService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private RemoteUserService remoteUserService; // 远程调用用户服务

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }


    @GetMapping("code1")
    public R<?> code1(String username)
    {
        // 商家获取验证码
        // 判断手机号是否存在
        if(!sysLoginService.checkUserExist(username)){
            return R.fail("手机号不存在");
        }
        // 获取验证码
        Random random = new Random();
        // 生成 100000~999999 之间的随机数 6位
        int code = random.nextInt(900000) + 100000;
        redisTemplate.opsForValue().set("myCode:"+username, String.valueOf(code),3, TimeUnit.MINUTES);
        HttpResponse sms = SmsTest.SMS(String.valueOf(code), username,"3");
        System.out.println("sms");
        System.out.println(sms);
        System.out.println("sms");
        return R.ok(String.valueOf(code),"有效期3分钟");
    }
    @PostMapping("login1")
    public R<?> login1(@RequestBody LoginBody1 form)
    {
        // 商家登录
        // 判断验证码是否存在
        Object code = redisTemplate.opsForValue().get("myCode:" + form.getUsername());
        if(code== null){
            return R.fail("验证码过期");
        }
        if (code.equals(form.getCode())){
            // 验证通过 删除redis中的验证码
            redisTemplate.delete("myCode:"+form.getUsername());
            // 获取这个手机号用户的用户名和密码 调用若依登录接口
            SysUser sysUser = sysLoginService.getSysUser(form.getUsername());
            System.out.println("用户信息是"+sysUser);
            String username = sysUser.getUserName();

            LoginUser user = sysLoginService.getInfo(username);

            List<SysRole> roles = user.getSysUser().getRoles();
            Long roleId = roles.get(0).getRoleId();//
            if(roleId==100L){
                return R.ok(tokenService.createToken(user));
            }else {
                return R.fail("您没有权限登录");
            }

        }
        return R.fail("验证码错误");
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    // 商家注册
    @PostMapping("register1")
    public R<?> register1(@RequestBody RegisterBody1 registerBody1) {

        // 判断验证码是否存在，是否正确
        Object code = redisTemplate.opsForValue().get("myCode:" + registerBody1.getPhone());
        if(code== null){
            return R.fail("验证码过期");
        }
        if (code.equals(registerBody1.getVerifyCode())){
            redisTemplate.delete("myCode:"+registerBody1.getPhone());
            sysLoginService.register1(registerBody1);
            return R.ok("注册成功");
        }else {
            return R.fail("验证码错误");
        }
    }

    // 用户注册
    @PostMapping("register2")
    public R<?> register2(@RequestBody RegisterBody2 registerBody) {
        return null;
    }

    // 商家注册时获取验证码
    @GetMapping("code2")
    public R<?> code2(String username) {
        // 生成随机6位验证码
        Random random = new Random();
        // 生成 100000~999999 之间的随机数 6位
        int code1 = random.nextInt(900000) + 100000;
        String code = String.valueOf(code1);
        // 判断手机号是否存在，存在给出提示，不能注册了
        if(sysLoginService.checkUserExist(username)){
            return R.fail("手机号已经注册了");
        }

        // 手机号不存在，发送验证码，保存验证码到redis中，有效期10分钟
        redisTemplate.opsForValue().set("myCode:"+username, code,15, TimeUnit.MINUTES);
        HttpResponse sms = SmsTest.SMS(code, username,"15");
        System.out.println("sms");
        System.out.println(sms);
        System.out.println("sms");
        return R.ok(code,"有效期15分钟");

    }


    @GetMapping("code3")
    public R<?> code3(String username) {
        // 用户 获取验证码
        Random random = new Random();
        // 获取 100000~999999 之间的随机数 6位
        int code = random.nextInt(900000) + 100000;
        redisTemplate.opsForValue().set("myCode:"+username, String.valueOf(code),3, TimeUnit.MINUTES);
        HttpResponse sms = SmsTest.SMS(String.valueOf(code), username,"15");
        System.out.println("sms");
        System.out.println(sms);
        System.out.println("sms");
        return R.ok(String.valueOf(code),"有效期3分钟");
    }
    @PostMapping("login2")
    public R<?> login2(@RequestBody LoginBody1 form)
    {

        // 判断验证码是否存在
        Object code = redisTemplate.opsForValue().get("myCode:" + form.getUsername());
        if(code== null){
            return R.fail("验证码过期");
        }
        // 验证码错误
        if (!code.equals(form.getCode())){
            return R.fail("验证码错误");
        }else{
            redisTemplate.delete("myCode:"+form.getUsername());

        }

        // 用户登录
        // 判断手机号是否存在
        if(!sysLoginService.checkUserExist(form.getUsername())){
            // 手机号不存在 走注册接口
            User user = new User();
            user.setPhone(form.getUsername());
            // 向user表添加数据
            Integer i = remoteUserService.registerUser(user, SecurityConstants.INNER);
            // 需要在sys_user系统用户表中添加数据
            SysUser sysUser = new SysUser();
            sysUser.setUserName(form.getUsername());
            sysUser.setNickName(form.getUsername());
            sysUser.setPhonenumber(form.getUsername());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setRemark("用户");
            Long l = sysLoginService.register2(sysUser);
            if(l*i>0){
                // 需要查询手机号的用户信息 然后生成token返回给前端
                return R.ok(tokenService.createToken(sysLoginService.getInfo(form.getUsername())),"注册成功");
            }else{
                return R.fail("注册失败");
            }
        }
        // 手机号存在，走登录接口

        SysUser sysUser = sysLoginService.getSysUser(form.getUsername());
        System.out.println("系统用户信息是："+sysUser);
        String userName = sysUser.getUserName();
        LoginUser user = sysLoginService.getInfo(userName);
        List<SysRole> roles = user.getSysUser().getRoles();
        Long roleId = roles.get(0).getRoleId();//
        if(roleId==101L){
            return R.ok(tokenService.createToken(user),"登录成功");
        }else {
            return R.fail("您没有权限登录");
        }




    }
}
